"""系统相关API路由"""

from flask import Blueprint, request, jsonify
import time
import logging
import psutil
import platform
import os
from datetime import datetime

from database import db_service
from config import get_config
from models import model_manager
from tracking import tracker_manager
from video_processing import camera_manager
from behavior_analysis import analysis_manager
from alerts import alert_manager
from .auth import token_required

# 创建蓝图
system_bp = Blueprint('system', __name__, url_prefix='/api/system')

# 配置日志
logger = logging.getLogger('api.system')

@system_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查接口
    
    返回系统健康状态
    
    返回:
    - {"status": "healthy", "service": "traffic-monitoring-api", "timestamp": 1634567890}
    """
    try:
        # 基本的健康检查
        health = {
            "status": "healthy",
            "service": "traffic-monitoring-api",
            "version": get_config('system.version', '1.0.0'),
            "timestamp": time.time(),
            "datetime": datetime.now().isoformat()
        }
        
        # 检查关键组件
        try:
            health["model"] = "initialized" if hasattr(model_manager, 'initialized') and model_manager.initialized else "unknown"
        except:
            health["model"] = "error"
        
        try:
            health["camera"] = "available" if hasattr(camera_manager, 'is_available') and camera_manager.is_available() else "unknown"
        except:
            health["camera"] = "error"
        
        return jsonify(health)
    except Exception as e:
        logger.error(f"健康检查错误: {str(e)}")
        return jsonify({
            'status': 'unhealthy', 
            'error': str(e),
            'timestamp': time.time()
        }), 500

@system_bp.route('/info', methods=['GET'])
@token_required
def get_system_info():
    """获取系统信息接口
    
    返回系统基本信息、组件状态和统计数据
    
    返回:
    - 系统名称、版本、组件状态和统计数据
    """
    try:
        # 获取系统统计信息
        days = int(request.args.get('days', 7))
        stats = db_service.get_statistics(days=days)
        
        # 获取组件状态
        components_status = {
            'model': model_manager.get_status(),
            'tracking': tracker_manager.get_status(),
            'camera': camera_manager.get_status(),
            'analysis': analysis_manager.get_status(),
            'alerts': len(alert_manager.get_active_alerts())
        }
        
        # 获取系统资源信息
        system_resources = get_system_resources()
        
        return jsonify({
            'system_name': get_config('system.name', '智能交通监管系统'),
            'system_version': get_config('system.version', '1.0.0'),
            'system_resources': system_resources,
            'statistics': stats,
            'components_status': components_status,
            'timestamp': time.time(),
            'datetime': time.strftime('%Y-%m-%d %H:%M:%S')
        })
    except Exception as e:
        logger.error(f"获取系统信息失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/statistics', methods=['GET'])
@token_required
def get_statistics():
    """获取统计信息接口
    
    查询参数:
    - days: 统计天数，默认7天
    - group_by: 分组方式 (day/hour/type)
    
    返回:
    - 按指定时间范围和分组方式的统计数据
    """
    try:
        days = int(request.args.get('days', 7))
        group_by = request.args.get('group_by', 'day')
        
        stats = db_service.get_statistics(days=days, group_by=group_by)
        
        # 直接返回统计数据，不嵌套在statistics对象中
        # 这样前端可以直接获取camera_count等字段
        return jsonify(stats)
    except ValueError:
        return jsonify({'error': '参数格式错误'}), 400
    except Exception as e:
        logger.error(f"获取统计信息失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/resources', methods=['GET'])
@token_required
def get_resources():
    """获取系统资源使用情况
    
    返回CPU、内存、磁盘使用情况等
    """
    try:
        resources = get_system_resources()
        
        return jsonify({
            'resources': resources,
            'timestamp': time.time()
        })
    except Exception as e:
        logger.error(f"获取系统资源信息失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/logs', methods=['GET'])
@token_required
def get_logs():
    """获取系统日志
    
    查询参数:
    - level: 日志级别 (debug/info/warning/error)
    - limit: 返回日志数量
    - offset: 偏移量
    - start_time: 开始时间 (可选)
    - end_time: 结束时间 (可选)
    - source: 日志来源 (可选)
    
    返回:
    - 系统日志列表
    """
    try:
        level = request.args.get('level', 'info')
        limit = int(request.args.get('limit', 50))
        offset = int(request.args.get('offset', 0))
        
        # 可选参数
        start_time = request.args.get('start_time')
        end_time = request.args.get('end_time')
        source = request.args.get('source')
        
        # 验证参数
        if limit > 1000:
            return jsonify({'error': 'limit参数不能超过1000'}), 400
        
        # 转换时间参数
        start_timestamp = None
        end_timestamp = None
        
        if start_time:
            try:
                start_timestamp = float(start_time)
            except ValueError:
                return jsonify({'error': 'start_time参数格式错误'}), 400
        
        if end_time:
            try:
                end_timestamp = float(end_time)
            except ValueError:
                return jsonify({'error': 'end_time参数格式错误'}), 400
        
        # 从数据库获取日志
        logs = db_service.get_system_logs(
            level=level, 
            limit=limit, 
            offset=offset,
            start_time=start_timestamp,
            end_time=end_timestamp,
            source=source
        )
        
        # 获取总数
        total = db_service.count_system_logs(
            level=level,
            start_time=start_timestamp,
            end_time=end_timestamp,
            source=source
        )
        
        # 计算分页信息
        pages = (total + limit - 1) // limit
        current_page = (offset // limit) + 1
        
        return jsonify({
            'logs': [{
                'id': log.id,
                'level': log.level,
                'message': log.message,
                'source': log.source,
                'created_at': log.created_at.isoformat(),
                'created_timestamp': log.created_at.timestamp()
            } for log in logs],
            'pagination': {
                'total': total,
                'pages': pages,
                'current_page': current_page,
                'limit': limit,
                'offset': offset
            },
            'filters': {
                'level': level,
                'source': source,
                'start_time': start_time,
                'end_time': end_time
            },
            'timestamp': time.time()
        })
    except ValueError:
        return jsonify({'error': '参数格式错误'}), 400
    except Exception as e:
        logger.error(f"获取系统日志失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/components/status', methods=['GET'])
@token_required
def get_components_status():
    """获取所有组件状态
    
    返回模型、跟踪、摄像头、分析、告警等组件的状态
    """
    try:
        components_status = {
            'model': model_manager.get_status(),
            'tracking': tracker_manager.get_status(),
            'camera': camera_manager.get_status(),
            'analysis': analysis_manager.get_status(),
            'alerts': alert_manager.get_status(),
            'database': db_service.get_status()
        }
        
        # 检查所有组件是否正常运行
        all_healthy = all(comp.get('status') == 'healthy' for comp in components_status.values())
        
        return jsonify({
            'all_healthy': all_healthy,
            'components': components_status,
            'timestamp': time.time()
        })
    except Exception as e:
        logger.error(f"获取组件状态失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/restart', methods=['POST'])
@token_required
def restart_system():
    """重启系统服务
    
    重启所有组件服务
    
    返回:
    - {"status": "restarting", "message": "系统正在重启..."}
    """
    try:
        # 记录重启日志
        logger.info("系统重启请求已接收")
        db_service.log_system_event("系统重启", "api", "info")
        
        # 重启各组件
        restart_results = {}
        
        try:
            if hasattr(model_manager, 'restart'):
                model_manager.restart()
                restart_results["model"] = "restarted"
        except Exception as e:
            restart_results["model"] = f"error: {str(e)}"
        
        try:
            if hasattr(tracker_manager, 'restart'):
                tracker_manager.restart()
                restart_results["tracking"] = "restarted"
        except Exception as e:
            restart_results["tracking"] = f"error: {str(e)}"
        
        try:
            if hasattr(camera_manager, 'restart'):
                camera_manager.restart()
                restart_results["camera"] = "restarted"
        except Exception as e:
            restart_results["camera"] = f"error: {str(e)}"
        
        try:
            if hasattr(analysis_manager, 'restart'):
                analysis_manager.restart()
                restart_results["analysis"] = "restarted"
        except Exception as e:
            restart_results["analysis"] = f"error: {str(e)}"
        
        return jsonify({
            'status': 'restarting',
            'message': '系统正在重启...',
            'components_status': restart_results,
            'timestamp': time.time(),
            'datetime': datetime.now().isoformat()
        })
    except Exception as e:
        logger.error(f"系统重启失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

@system_bp.route('/version', methods=['GET'])
@token_required
def get_version():
    """获取系统版本信息
    
    返回系统版本、API版本等信息
    """
    try:
        return jsonify({
            'system_version': get_config('system.version', '1.0.0'),
            'api_version': get_config('api.version', 'v1'),
            'build_date': get_config('system.build_date', 'unknown'),
            'build_number': get_config('system.build_number', '0')
        })
    except Exception as e:
        logger.error(f"获取版本信息失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500

def get_system_resources():
    """获取系统资源使用情况
    
    Returns:
        系统资源信息字典
    """
    try:
        # 获取CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 获取内存使用情况
        memory = psutil.virtual_memory()
        
        # 获取磁盘使用情况 - 支持多平台
        disk_path = '/'  # 默认路径
        if platform.system() == 'Windows':
            # 在Windows系统上使用当前磁盘或C盘
            disk_path = os.path.abspath(os.sep)  # 获取系统根目录
        
        disk = psutil.disk_usage(disk_path)
        
        # 获取进程数量
        process_count = len(psutil.pids())
        
        # 获取网络信息
        network = psutil.net_io_counters()
        
        # 系统信息
        system_info = {
            'os': platform.system(),
            'os_version': platform.version(),
            'python_version': platform.python_version(),
            'machine': platform.machine(),
            'processor': platform.processor(),
            'hostname': platform.node()
        }
        
        # 获取负载信息（如果可用）
        load_info = None
        if hasattr(os, 'getloadavg'):
            try:
                load_avg = os.getloadavg()
                load_info = {
                    "1min": load_avg[0],
                    "5min": load_avg[1],
                    "15min": load_avg[2]
                }
            except:
                pass
        
        return {
            'cpu': {
                'percent': cpu_percent,
                'cores': psutil.cpu_count(logical=True),
                'physical_cores': psutil.cpu_count(logical=False),
                'load': load_info
            },
            'memory': {
                'total': memory.total,
                'available': memory.available,
                'used': memory.used,
                'percent': memory.percent,
                'free': memory.free
            },
            'disk': {
                'path': disk_path,
                'total': disk.total,
                'used': disk.used,
                'free': disk.free,
                'percent': disk.percent
            },
            'process_count': process_count,
            'network': {
                'bytes_sent': network.bytes_sent,
                'bytes_recv': network.bytes_recv,
                'packets_sent': network.packets_sent,
                'packets_recv': network.packets_recv,
                'errin': network.errin,
                'errout': network.errout
            },
            'system': system_info,
            'uptime': time.time() - psutil.boot_time(),
            'datetime': datetime.now().isoformat()
        }
    except Exception as e:
        logger.warning(f"获取系统资源信息失败: {str(e)}")
        return {}

@system_bp.route('/performance', methods=['GET'])
@token_required
def get_performance_metrics():
    """获取系统性能指标
    
    返回检测速度、FPS等性能指标
    """
    try:
        # 获取性能指标
        performance = {
            'system': {
                'cpu_percent': psutil.cpu_percent(interval=0.1),
                'memory_percent': psutil.virtual_memory().percent,
                'process_count': len(psutil.pids())
            },
            'detection': model_manager.get_performance_metrics() if hasattr(model_manager, 'get_performance_metrics') else {},
            'tracking': tracker_manager.get_performance_metrics() if hasattr(tracker_manager, 'get_performance_metrics') else {},
            'cameras': camera_manager.get_performance_metrics() if hasattr(camera_manager, 'get_performance_metrics') else {}
        }
        
        # 添加网络性能指标
        try:
            net_io = psutil.net_io_counters()
            performance['network'] = {
                'bytes_sent': net_io.bytes_sent,
                'bytes_recv': net_io.bytes_recv,
                'packets_sent': net_io.packets_sent,
                'packets_recv': net_io.packets_recv
            }
        except Exception as e:
            logger.warning(f"获取网络性能指标失败: {str(e)}")
        
        # 添加当前进程性能指标
        try:
            process = psutil.Process(os.getpid())
            with process.oneshot():
                performance['process'] = {
                    'cpu_percent': process.cpu_percent(interval=0.1),
                    'memory_percent': process.memory_percent(),
                    'threads': len(process.threads())
                }
        except Exception as e:
            logger.warning(f"获取进程性能指标失败: {str(e)}")
        
        return jsonify({
            'performance': performance,
            'timestamp': time.time(),
            'datetime': datetime.now().isoformat()
        })
    except Exception as e:
        logger.error(f"获取性能指标失败: {str(e)}")
        return jsonify({'error': f'服务器内部错误: {str(e)}'}), 500